package zy.service.shop.kpiassess.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import zy.dao.base.emp.EmpRewardDAO;
import zy.dao.base.shop.ShopRewardDAO;
import zy.dao.shop.kpiassess.KpiAssessDAO;
import zy.entity.PageData;
import zy.entity.PageInfo;
import zy.entity.base.emp.T_Base_EmpGroupList;
import zy.entity.base.emp.T_Base_Emp_Reward;
import zy.entity.base.shop.T_Base_Shop_Reward;
import zy.entity.shop.kpiassess.T_Shop_KpiAssess;
import zy.entity.shop.kpiassess.T_Shop_KpiAssessList;
import zy.entity.shop.kpiassess.T_Shop_KpiAssessReward;
import zy.entity.sys.user.T_Sys_User;
import zy.service.shop.kpiassess.KpiAssessService;
import zy.util.CommonUtil;
import zy.util.DateUtil;
import zy.util.StringUtil;
import zy.vo.shop.KpiAssessVO;

@Service
public class KpiAssessServiceImpl implements KpiAssessService{
	@Resource
	private KpiAssessDAO kpiAssessDAO;
	@Resource
	private ShopRewardDAO shopRewardDAO;
	@Resource
	private EmpRewardDAO empRewardDAO;
	
	@Override
	public PageData<T_Shop_KpiAssess> page(Map<String, Object> params) {
		Object companyid = params.get(CommonUtil.COMPANYID);
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		Integer pageSize = (Integer)params.get(CommonUtil.PAGESIZE);
		Integer pageIndex = (Integer)params.get(CommonUtil.PAGEINDEX);
		
		Integer totalCount = kpiAssessDAO.count(params);
		PageInfo pageInfo = new PageInfo(totalCount, pageSize, pageIndex);
		params.put(CommonUtil.START, (pageIndex-1)*pageSize);
		params.put(CommonUtil.END, pageSize);
		
		List<T_Shop_KpiAssess> list = kpiAssessDAO.list(params);
		PageData<T_Shop_KpiAssess> pageData = new PageData<T_Shop_KpiAssess>();
		pageData.setPageInfo(pageInfo);
		pageData.setList(list);
		return pageData;
	}
	
	@Override
	public List<T_Shop_KpiAssess> list4cashier(Map<String, Object> params) {
		Object companyid = params.get(CommonUtil.COMPANYID);
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		return kpiAssessDAO.list4cashier(params);
	}
	
	@Override
	public T_Shop_KpiAssess load(Integer ka_id) {
		return kpiAssessDAO.load(ka_id);
	}
	
	@Override
	public Map<String, Object> loadDetail(Map<String, Object> params) {
		String number = StringUtil.trimString(params.get("number"));
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<Map<String, Object>> header = kpiAssessDAO.loadHeader(number, companyid);
		List<T_Shop_KpiAssessList> kpiAssessLists = kpiAssessDAO.loadDetail(number, companyid);
		
		for (T_Shop_KpiAssessList item : kpiAssessLists) {
			if(StringUtil.isEmpty(item.getReward_codes())){
				continue;
			}
			String[] temps = item.getReward_codes().split("#");
			if(temps.length == 2){
				item.setReward_codes(temps[0]);
				item.setReward_names(temps[1]);
			}else {
				item.setReward_codes("");
				item.setReward_names("");
			}
		}
		//按照总分对表头排序
		final Map<String, Integer> totalScoreMap = new HashMap<String, Integer>();
		for (T_Shop_KpiAssessList item : kpiAssessLists) {
			if(totalScoreMap.containsKey(item.getKal_code())){
				totalScoreMap.put(item.getKal_code(), totalScoreMap.get(item.getKal_code())+item.getKal_score());
			}else {
				totalScoreMap.put(item.getKal_code(), item.getKal_score());
			}
		}
		Collections.sort(header, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                int c = 0;
                c = totalScoreMap.get(o1.get("kal_code").toString()) >= totalScoreMap.get(o2.get("kal_code").toString()) ? 1 : -1;
                return  -c;
            }
        });
		resultMap.put("header", header);
		resultMap.put("details", KpiAssessVO.buildDetailJson(kpiAssessLists));
		return resultMap;
	}
	
	@Override
	public Map<String, Object> statDetail(Map<String, Object> params) {
		String number = StringUtil.trimString(params.get("number"));
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		List<Map<String, Object>> header = kpiAssessDAO.loadHeader(number, companyid);
		T_Shop_KpiAssess kpiAssess = kpiAssessDAO.load(number, companyid);
		params.put("begin", kpiAssess.getKa_begin());
		params.put("end", kpiAssess.getKa_end()+" 23:59:59");
		params.put("ka_type", kpiAssess.getKa_type());
		List<T_Shop_KpiAssessList> kpiAssessLists = kpiAssessDAO.statDetail(params);
		//按照总分对表头排序
		final Map<String, Integer> totalScoreMap = new HashMap<String, Integer>();
		for (T_Shop_KpiAssessList item : kpiAssessLists) {
			if(totalScoreMap.containsKey(item.getKal_code())){
				totalScoreMap.put(item.getKal_code(), totalScoreMap.get(item.getKal_code())+item.getKal_score());
			}else {
				totalScoreMap.put(item.getKal_code(), item.getKal_score());
			}
		}
		Collections.sort(header, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                int c = 0;
                c = totalScoreMap.get(o1.get("kal_code").toString()) >= totalScoreMap.get(o2.get("kal_code").toString()) ? 1 : -1;
                return -c;
            }
        });
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("header", header);
		resultMap.put("details", KpiAssessVO.buildDetailJson(kpiAssessLists));
		return resultMap;
	}
	
	@Override
	@Transactional
	public void save(T_Shop_KpiAssess kpiAssess,List<T_Shop_KpiAssessList> kpiAssessLists, T_Sys_User user) {
		if(StringUtil.isEmpty(kpiAssess.getKa_type())){
			throw new IllegalArgumentException("ka_type不能为空");
		}
		if(StringUtil.isEmpty(kpiAssess.getKa_begin())){
			throw new IllegalArgumentException("ka_begin不能为空");
		}
		if(StringUtil.isEmpty(kpiAssess.getKa_end())){
			throw new IllegalArgumentException("ka_end不能为空");
		}
		if (kpiAssessLists == null || kpiAssessLists.size() == 0) {
			throw new IllegalArgumentException("请选择考核范围及KPI指标");
		}
		kpiAssess.setKa_state(0);
		kpiAssess.setKa_sysdate(DateUtil.getCurrentTime());
		kpiAssess.setKa_shop_code(user.getUs_shop_code());
		kpiAssess.setKa_us_id(user.getUs_id());
		kpiAssess.setCompanyid(user.getCompanyid());
		kpiAssessDAO.save(kpiAssess, kpiAssessLists);
	}
	
	@Override
	@Transactional
	public T_Shop_KpiAssess complete(T_Shop_KpiAssess kpiAssess,List<T_Shop_KpiAssessList> kpiAssessLists) {
		T_Shop_KpiAssess checkAssess = kpiAssessDAO.load(kpiAssess.getKa_id());
		if(checkAssess == null){
			throw new RuntimeException("KPI考核不存在");
		}
		if(!checkAssess.getKa_state().equals(0)){
			throw new RuntimeException("KPI考核已总结，请勿重复操作");
		}
		checkAssess.setKa_state(1);
		checkAssess.setKa_summary(kpiAssess.getKa_summary());
		List<T_Shop_KpiAssessReward> rewards = new ArrayList<T_Shop_KpiAssessReward>();
		Map<String, String> kpiNameMap = new HashMap<String, String>();
		for (T_Shop_KpiAssessList item : kpiAssessLists) {
			if(StringUtil.isNotEmpty(item.getReward_codes())){
				String[] rwCodes = item.getReward_codes().split(",");
				for (String rwCode : rwCodes) {
					T_Shop_KpiAssessReward reward = new T_Shop_KpiAssessReward();
					reward.setKar_number(checkAssess.getKa_number());
					reward.setKar_kal_code(item.getKal_code());
					reward.setKar_ki_code(item.getKal_ki_code());
					reward.setKar_rw_code(rwCode);
					reward.setCompanyid(checkAssess.getCompanyid());
					rewards.add(reward);
				}
			}
			if(!kpiNameMap.containsKey(item.getKal_ki_code())){
				kpiNameMap.put(item.getKal_ki_code(), item.getKi_name());
			}
		}
		List<T_Base_Shop_Reward> shopRewards = null;
		List<T_Base_Emp_Reward> empRewards = null;
		if (rewards.size() > 0) {
			if(CommonUtil.KPI_ASSESS_TYPE_SHOP.equals(checkAssess.getKa_type())){
				shopRewards = new ArrayList<T_Base_Shop_Reward>();
				for (T_Shop_KpiAssessReward reward : rewards) {
					T_Base_Shop_Reward shopReward = new T_Base_Shop_Reward();
					shopReward.setSr_sp_code(reward.getKar_kal_code());
					shopReward.setSr_rw_code(reward.getKar_rw_code());
					shopReward.setSr_sysdate(DateUtil.getCurrentTime());
					shopReward.setSr_state(0);
					shopReward.setSr_remark("KPI考核获得奖励,单据编号["+checkAssess.getKa_number()+"],指标名称["+StringUtil.trimString(kpiNameMap.get(reward.getKar_ki_code()))+"]。");
					shopReward.setCompanyid(checkAssess.getCompanyid());
					shopRewards.add(shopReward);
				}
			}else if(CommonUtil.KPI_ASSESS_TYPE_EMPGROUP.equals(checkAssess.getKa_type())){
				//查询员工组员工，针对员工组发放奖励，是针对员工组内员工发放奖励
				List<String> groupCodes = new ArrayList<String>();
				for (T_Shop_KpiAssessReward reward : rewards) {
					if(!groupCodes.contains(reward.getKar_kal_code())){
						groupCodes.add(reward.getKar_kal_code());
					}
				}
				List<T_Base_EmpGroupList> empGroupLists = kpiAssessDAO.loadEmpByGroup(groupCodes, checkAssess.getCompanyid());
				Map<String, List<String>> group_emp = new HashMap<String, List<String>>();
				for (T_Base_EmpGroupList item : empGroupLists) {
					if(!group_emp.containsKey(item.getEgl_eg_code())){
						group_emp.put(item.getEgl_eg_code(),new ArrayList<String>());
					}
					group_emp.get(item.getEgl_eg_code()).add(item.getEgl_em_code());
				}
				empRewards = new ArrayList<T_Base_Emp_Reward>();
				for (T_Shop_KpiAssessReward reward : rewards) {
					List<String> emps = group_emp.get(reward.getKar_kal_code());
					if (emps == null || emps.size() == 0) {
						continue;
					}
					for (String em_code : emps) {
						T_Base_Emp_Reward empReward = new T_Base_Emp_Reward();
						empReward.setEr_em_code(em_code);
						empReward.setEr_rw_code(reward.getKar_rw_code());
						empReward.setEr_sysdate(DateUtil.getCurrentTime());
						empReward.setEr_state(0);
						empReward.setEr_remark("KPI考核获得奖励,单据编号["+checkAssess.getKa_number()+"],指标名称["+StringUtil.trimString(kpiNameMap.get(reward.getKar_ki_code()))+"]。");
						empReward.setCompanyid(checkAssess.getCompanyid());
						empRewards.add(empReward);
					}
				}
			}else if(CommonUtil.KPI_ASSESS_TYPE_EMP.equals(checkAssess.getKa_type())){
				empRewards = new ArrayList<T_Base_Emp_Reward>();
				for (T_Shop_KpiAssessReward reward : rewards) {
					T_Base_Emp_Reward empReward = new T_Base_Emp_Reward();
					empReward.setEr_em_code(reward.getKar_kal_code());
					empReward.setEr_rw_code(reward.getKar_rw_code());
					empReward.setEr_sysdate(DateUtil.getCurrentTime());
					empReward.setEr_state(0);
					empReward.setEr_remark("KPI考核获得奖励,单据编号["+checkAssess.getKa_number()+"],指标名称["+StringUtil.trimString(kpiNameMap.get(reward.getKar_ki_code()))+"]。");
					empReward.setCompanyid(checkAssess.getCompanyid());
					empRewards.add(empReward);
				}
			}
		}
		
		kpiAssessDAO.complete(checkAssess);
		kpiAssessDAO.completeDetail(kpiAssessLists);
		if (rewards.size() > 0) {
			kpiAssessDAO.saveReward(rewards);
			if (shopRewards != null && shopRewards.size() > 0) {
				shopRewardDAO.save(shopRewards);
			}
			if (empRewards != null && empRewards.size() > 0) {
				empRewardDAO.save(empRewards);
			}
		}
		return checkAssess;
	}
	
	@Override
	@Transactional
	public void del(Integer ka_id) {
		T_Shop_KpiAssess kpiAssess = kpiAssessDAO.load(ka_id);
		if(kpiAssess == null){
			throw new RuntimeException("KPI考核不存在");
		}
		if(!kpiAssess.getKa_state().equals(0)){
			throw new RuntimeException("KPI考核已总结，不能删除");
		}
		kpiAssessDAO.del(kpiAssess.getKa_number(), kpiAssess.getCompanyid());
	}
	
}
